//
//  GYDImagePickerViewController.swift
//  Weibo
//
//  Created by 贵永冬 on 16/7/30.
//  Copyright © 2016年 贵永冬. All rights reserved.
//

import UIKit
import ReactiveCocoa
import SVProgressHUD

class GYDImagePickerViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate , UIScrollViewDelegate{

    var selectedIndex : Int = 1
    var allImageUrl : [String]?
    var cellFrameDic : [Int : NSValue]?
    var imageSize : [Int : NSValue]?
    var label : UILabel?
    var collectionView : UICollectionView?
    var moreButton : UIButton?
    
    var showImageView : UIImageView?
    
    /// 模态动画管理者
    private var manager : GYDPopPresentationManager?
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        let manager = GYDPopPresentationManager()
        self.manager = manager
        manager.presentFrame = CGRect(x: 0, y: 0, width: GYDWindowWidth , height: GYDWindowHeight)
        self.transitioningDelegate = manager
        self.modalPresentationStyle = UIModalPresentationStyle.Custom
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.dismissViewControllerAnimated(false, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.clearColor()
    }
    
    func showAnimation() {
        let imageFrame = cellFrameDic![selectedIndex]?.CGRectValue()
        let showImageView = UIImageView(frame: imageFrame!)
        showImageView.contentMode = UIViewContentMode.ScaleAspectFill
        self.showImageView = showImageView
        var url = allImageUrl![selectedIndex]
        showImageView.sd_setImageWithURL(NSURL(string:url))
        url = url.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        showImageView.sd_setImageWithURL(NSURL(string:url))
        view.addSubview(showImageView)
        let size = imageSize![selectedIndex]?.CGSizeValue()
        UIView.animateWithDuration(0.4, animations: {
            
            showImageView.size = CGSize(width: GYDWindowWidth, height: GYDWindowHeight*((size?.width)!/GYDWindowWidth))
            showImageView.center = CGPoint(x: GYDWindowWidth/2.0, y: GYDWindowHeight/2.0)
            }) { (stop) in
                self.showImageView?.hidden = true
                self.createCollectionView()
                self.createTopView()
                self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: self.selectedIndex,inSection: 0), atScrollPosition: UICollectionViewScrollPosition.None, animated: false)
        }
    }
    
    func createTopView() {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 80, height: 44))
        label.center = CGPoint(x: GYDWindowWidth/2.0, y: 22 + 20)
        label.textColor = UIColor.whiteColor()
        label.font = UIFont.boldSystemFontOfSize(19)
        view.addSubview(label)
        self.label = label
        label.textAlignment = NSTextAlignment.Center
        label.text = String(format: "%ld/%ld", selectedIndex+1,(allImageUrl?.count)!)
        
        let button = UIButton(type: UIButtonType.Custom)
        moreButton = button
        button.frame = CGRect(x: GYDWindowWidth - 60, y: 20, width: 44, height: 44)
        button.setImage(UIImage(named: "navigationbar_more_light"), forState: UIControlState.Normal)
        button.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { [unowned self] (x) in
            GYDBottomPopView.showWithTitleArray(["保存图片","转发微博","赞"], selectedBlock: { (index) in
                if index == 0 {
                    let cell = self.collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: self.selectedIndex, inSection: 0)) as! GYDImagePickerCell
                    TZImageManager().savePhotoWithImage(cell.imageView?.image, completion: { 
                        SVProgressHUD.showSuccessWithStatus("保存成功")
                        dissmissHudView(0.8)
                    })
                }
                }, dissmissBlock: nil)
        }
        view.addSubview(button)
    }
    
    func createCollectionView() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: GYDWindowWidth, height: GYDWindowHeight)
        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        view.addSubview(collectionView)
        collectionView.pagingEnabled = true
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = false
        collectionView.registerClass(GYDImagePickerCell.classForCoder(), forCellWithReuseIdentifier: "cellId")
        collectionView.delegate = self
        collectionView.dataSource = self
        self.collectionView = collectionView
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        showAnimation()
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return allImageUrl?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath) as! GYDImagePickerCell
        cell.resetView()
        var url = allImageUrl![indexPath.item]
        url = url.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        cell.indicatorView.startAnimating()
        cell.imageView?.sd_setImageWithURL(NSURL(string: url), completed: { (image, error, _, _) in
            cell.indicatorView.stopAnimating()
        })
        
        cell.selectedBlock = { [unowned self] (image : UIImage?) -> () in
            if image == nil {
                self.dismissViewControllerAnimated(false, completion: nil)
            }
            
            self.showImageView?.image = image
            self.showImageView?.hidden = false
            self.showImageView?.size = image!.size
            self.showImageView?.center = CGPoint(x: GYDWindowWidth/2.0, y: GYDWindowHeight/2.0)
            let frame = self.cellFrameDic![self.selectedIndex]?.CGRectValue()
            self.collectionView?.alpha = 0.0
            self.label?.alpha = 0.0
            self.moreButton?.alpha = 0.0
            UIView.animateWithDuration(0.4, animations: {
                self.showImageView?.frame = frame!
            }) { (stop) in
                self.dismissViewControllerAnimated(false, completion: nil)
            }
        }
        return cell
    }
    
    
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x / GYDWindowWidth)
        self.selectedIndex = index
        self.label!.text = String(format: "%ld/%ld", selectedIndex+1,(allImageUrl?.count)!)
    }
    
    deinit {
        print("图片控制器消失")
    }
    
}

class GYDImagePickerCell: UICollectionViewCell,UIScrollViewDelegate {
    
    var imageView : UIImageView?
    var scrollView : UIScrollView?
    
    var selectedBlock : ((image:UIImage?) -> ())?
    /// 提示视图
    lazy var indicatorView : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        scrollView = UIScrollView()
        scrollView?.backgroundColor = UIColor.clearColor()
        scrollView?.maximumZoomScale = 2.0
        scrollView?.minimumZoomScale = 0.5
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.delegate = self
        contentView.addSubview(scrollView!)
        scrollView!.snp_makeConstraints(closure: { (make) in
            make.left.equalTo(0)
            make.bottom.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(0)
        })
        
        imageView = UIImageView()
        imageView!.contentMode = UIViewContentMode.ScaleAspectFit
        scrollView!.addSubview(imageView!)
        imageView!.snp_makeConstraints(closure: { (make) in
            make.width.equalTo(GYDWindowWidth)
            make.height.equalTo(GYDWindowHeight)
            make.center.equalTo((scrollView?.snp_center)!)
        })
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(GYDImagePickerCell.tap))
        scrollView?.addGestureRecognizer(tap)
        
        indicatorView.center = contentView.center
        contentView.addSubview(indicatorView)
        
    }
    @objc private func tap() {
        if selectedBlock != nil {
            selectedBlock!(image:self.imageView?.image)
        }
    }
    func resetView() {
        scrollView!.contentSize = CGSizeZero
        scrollView!.contentInset = UIEdgeInsetsZero
        scrollView!.contentOffset = CGPointZero
        
        imageView!.transform = CGAffineTransformIdentity
    }
    
    //MARK: -UIScrollViewDelegate
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    // 缩放的过程中会不断调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
        let width = UIScreen.mainScreen().bounds.width
        let height = UIScreen.mainScreen().bounds.height
        
        // 1.计算上下内边距
        var offsetY = (height - imageView!.frame.height) * 0.5
        // 2.计算左右内边距
        var offsetX = (width - imageView!.frame.width) * 0.5
        
        offsetY = (offsetY < 0) ? 0 : offsetY
        offsetX = (offsetX < 0) ? 0 : offsetX
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
}

